
var PlayLayer = cc.Layer.extend({
        bgSprite : null, 
    SushiSprites : null,
    car : null, 
    score : 0,
    timeout : 60,            //游戏时间
    distance : 0,
    add_time_gap : 0.1,     //添加小球的时间间隔 
    drop_time_gap : 1.5,      //小球下坠的时间
    add_speed : 6,          //多少个gap下一个球
    cycle : 0,
    ctor:function(){
                this._super();

                var size = cc.winSize;

                //添加背景
                this.bgSprite = new cc.Sprite(res.bg);
                this.bgSprite.attr({
                        x: size.width / 2,
                        y: size.height / 2,
                        rotation: 180
                });

                this.addChild(this.bgSprite, 0);

                this.scheduleUpdate(); 

                //添加倒计时
                this.schedule(this.onTimer, 1, this.timeout, 0);

                //增加sprite定时器
                this.schedule(this.myupdate, this.add_time_gap, cc.REPEAT_FOREVER, 1);


                
                //精灵数组
                this.SushiSprites = [];


                //添加分数
                this.scoreLabel = new cc.LabelTTF("score:0", "", 20);
                this.scoreLabel.attr({
                        x: size.width - 80,
                        y: size.height  - 20,
                        color: cc.color(0, 0, 255),
                });
                this.addChild(this.scoreLabel, 6);

                //添加倒计时
                this.timeoutLabel = new cc.LabelTTF("" + this.timeout, "", 30);
                this.timeoutLabel.attr ({
                        x: 30,
                        y: size.height - 20,
                        color: cc.color(0, 0, 255),
                });
                this.addChild(this.timeoutLabel, 6);


                //增加距离显示
                /*
                this.disLabel = new cc.LabelTTF("distance:" + this.distance, "", 20);
                this.disLabel.attr({
                        x: size.width / 2 - 10,
                        y: size.height - 20,
                        color: cc.color(0,0, 255)
                });
                this.addChild(this.disLabel, 6);
                */

                this.last_score_label = new cc.LabelTTF("" , "", 20);
                this.last_score_label.attr({
                        x: size.width  - 20,
                        y: size.height - 20,
                        color: cc.color(255,0, 0)
                });
                this.addChild(this.last_score_label, 6);

                //添加汽车
                this.addCar();


                return true;
    },

    update : function() {
        this.checkHit();
    },

    myupdate : function(){
        this.cycle += 1;
        if (this.add_speed <=0 || this.cycle % this.add_speed == 0) {
                this.addSushi();
        }

        this.removeSushi();
        console.log("len:" + this.SushiSprites.length);
    },

    addScore : function(score) {
        var rscore = Math.round(score);
        this.score += rscore; 
        if (this.score < 0) {
                rscore -= this.score;
                this.score = 0; 
        }
        this.scoreLabel.setString("score:" + this.score);
        
        if (rscore != 0){
                if (rscore > 0){
                        //this.last_score_label.setColor(cc.Color(0,255,0));
                        this.last_score_label.setString("+" + rscore);

                }
                else if (rscore < 0) {
                        //this.last_score_label.setColor(cc.Color(255,0,0));
                        this.last_score_label.setString(rscore);
                }
        }

    },

    addDis : function(dis) {
            this.distance += dis;
            this.distance = Math.round(this.distance);
            this.disLabel.setString("distance:" + this.distance);
    },

    //检查是否碰撞了
    checkHit : function() {
        var rect_car = this.car.getBoundingBox();
        for (var i = 0; i < this.SushiSprites.length; i ++) {
                var rect = this.SushiSprites[i].getBoundingBox();
                if (cc.rectIntersectsRect(rect_car, rect)) { 
                        //碰撞上啦
                        this.SushiSprites[i].runDisappear(this.SushiSprites[i]);

                        this.SushiSprites[i] = undefined;
                        this.SushiSprites.splice(i, 1);
                        i = i - 1;
                } 
        }
    },

    addCar : function(){
            this.car = new CarSprite(res.car);
            var size = cc.winSize;

            this.car.setScaleX(0.25);
            this.car.setScaleY(0.25);

            this.car.attr({
                    x: size.width / 2,
                    y: 20,
            });
            this.addChild(this.car, 6);
    },

    //添加sprite
    addSushi : function() {

        var sushi;
        if (cc.random0To1() < 0.5)
        {
                sushi = new SushiSprite(res.sushi_black);
                sushi.type = 1;
        }
        else {
                sushi = new SushiSprite(res.sushi);
                sushi.type = 2;
        }

        var scale = 0.3 + cc.random0To1()/2;
        sushi.setScaleX(scale);
        sushi.setScaleY(scale);
        var size = cc.winSize;
        sushi._scale = scale * 10; 

        var x = sushi.width / 2 + (size.width - sushi.width)  * cc.random0To1();
        sushi.attr({
                x: x,
                y: size.height + sushi.height / 2 ,
        });

        this.addChild(sushi, 5);


        //添加动画
        var dropAction = cc.MoveTo.create(this.drop_time_gap, cc.p(sushi.x, -sushi.height));
        sushi.runAction(dropAction);

        this.SushiSprites.push(sushi);
    },

    //删除已经超出视野的sprite
    removeSushi : function() {
        for (var i = 0; i < this.SushiSprites.length; i ++) {
                if ( 0 >= this.SushiSprites[i].y)
                {
                    this.SushiSprites[i].removeFromParent();
                    this.SushiSprites[i] = undefined;
                    this.SushiSprites.splice(i, 1);
                    i = i - 1;
                }
        }
    },

    onTimer : function() {
            if (this.timeout == 0)
            {

                    //游戏结束了
                    var gameOver = new cc.LayerColor(cc.color(225,0,0,100));
                    var size = cc.winSize;
                    var titleLabel = new cc.LabelTTF("Game Over", "Arial", 38);
                    titleLabel.attr({
                            x:size.width / 2 ,
                            y:size.height / 2 + 10
                    });
                    gameOver.addChild(titleLabel, 10);


                    var touchlistener = cc.EventListener.create({
                            event : cc.EventListener.TOUCH_ONE_BY_ONE,
                            swallowTouches: false,
                            onTouchBegan : function(touch, event) {
                                    console.log("gameOver onTouchBegan...");
                                    return true;        
                            },
                    });

                   
                    cc.eventManager.addListener(touchlistener, gameOver); 


                    /***************************************************/
                    //重试菜单
                    var TryAgainItem = new cc.MenuItemFont(
                                    "Try Again",
                                    function () {
                                            cc.log("Menu is clicked!");
                                            cc.director.runScene(new PlayScene());
                                    }, this);
                    TryAgainItem.attr({
                            x: size.width/2,
                            y: size.height / 2 - 40,
                            anchorX: 0.5,
                            anchorY: 0.5
                    });

                    /***************************************************/
                    //回退菜单
                    var BackItem = new cc.MenuItemFont(
                                    "Go Back",
                                    function() { 
                                            console.log("Go Back is clicked!");
                                            cc.director.popScene();
                                    }, this);
                    BackItem.attr({
                            x: size.width / 2,
                            y: size.height / 2 - 80,
                            anchorX: 0.5,
                            anchorY: 0.5,
                    });


                    /***************************************************/
                    //分享按钮
                    /*
                    var ShareItem = new cc.MenuItemFont(
                                    "Share",
                                    function() {
                                                    if (typeof WeixinJSBridge == "undefined") {
                                                            alert("请先通过微信搜索 wow36kr 添加36氪为好友，通过微信分享文章 :) ");
                                                    } else {
                                                            WeixinJSBridge.invoke('shareTimeline', {
                                                                    "title": "36氪",
                                                                    "link": "http://www.36kr.com",
                                                                    "desc": "关注互联网创业",
                                                                    "img_url": "http://www.36kr.com/assets/images/apple-touch-icon.png"
                                                            }, function(d){
                                                                    alert(d.err_msg); 
                                                            });
                                                    }

                                    }, this);
                    ShareItem.attr({
                            x: size.width / 2,
                            y: size.height / 2 - 105,
                            anchorX: 0.5,
                            anchorY: 0.5,
                    });
                    */



                    var menuItems = [TryAgainItem, BackItem/*, ShareItem*/];
                    var menu = new cc.Menu(menuItems);
                    menu.x = 0;
                    menu.y = 0;


                    gameOver.addChild(menu, 1);
                    //添加浮层
                    this.getParent().addChild(gameOver);

                    //移除汽车的事件
                    this.car.removeListener();

                    this.unschedule(this.myupdate);
                    this.unschedule(this.timer);
                    return ;
            }

            this.timeout  -= 1;
            this.timeoutLabel.setString("" + this.timeout);

            this.add_speed = Math.round(this.timeout / 10);
            
    },
});

var PlayScene = cc.Scene.extend ({
        onEnter:function() {
                this._super();
                var layer = new PlayLayer();
                this.addChild(layer); 
        }
});
